var ReservationsStoreRecordsTable = { // 预约建档初始化
    id: "ReservationsStoreRecordsTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

function _formatter(value, row, index) {
    if (row.dealStatus === "已结账") {
        return '<span style="color: green" title="' + value + '">' + value + '</span>'
    } else {
        return '<span title="' + value + '">' + value + '</span>'
    }
}

function _formatterTime(value, row, index) {
    if (row.dealStatus === "已结账") {
        return "<span style='color: green'>" + value.substring(0, 19) + "</span>"
    } else {
        return value.substring(0, 19);
    }
}

function _formatterTitle(value, row, index) {
    if (row.huifang === "" || row.huifang == null) {
        row.huifang = "无回访详情";
    } else {
        row.huifang = ",<b>" + "回访详情：" + row.huifang.replace(/\s{2,}/g, "");
        var reg = /,<b>/g;
        var regs = /<\/b>/g;
        row.huifang = row.huifang.replace(reg, '&#10;');
        row.huifang = row.huifang.replace(regs, ' ');
    }
    if (row.dealStatus === "已结账") {
        return "<span style='color: green; cursor:pointer' title='" + row.huifang + "' >" + value.substring(0, 19) + "</span>"
    } else {
        return "<span style=' cursor:pointer' title='" + row.huifang + "' >" + value.substring(0, 19) + "</span>"
    }
}

ReservationsStoreRecordsTable.initColumn = function () { // 初始化表格的列
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '', field: 'id', visible: false, align: 'center', valign: 'middle'},
        {title: '', field: 'customerSexHead ', visible: false, align: 'center', valign: 'middle'},
        {title: '预约号', field: 'reservationsNum', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '标识号', field: 'identificationNumber', align: 'center', valign: 'middle', sortable: true, width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '客户姓名', field: 'customerName', align: 'center', valign: 'middle', sortable: true, width: 120,
            formatter: function (value, row, index) {
                if (row.dealStatus === "已结账") {
                    return "<a href='javascript:;' style='display: flex;align-items: center;color: green' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                } else {
                    return "<a href='javascript:;' style='display: flex;align-items: center;' ><img src='" + row.customerSexHead + "' alt='' width='40px'><span class='portraitHeadName'>" + value + "</span></a>"
                }
            }
        },
        {title: '手机号码', field: 'customerPhone', align: 'center', valign: 'middle', sortable: true, width: 140,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '初诊门诊', field: 'arrivalStore', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '建档人', field: 'archiving', align: 'center', valign: 'middle', sortable: true, width: 90,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '跟进人', field: 'follower', align: 'center', valign: 'middle', sortable: true, width: 90,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '归属人', field: 'belonger', align: 'center', valign: 'middle', sortable: true, width: 90,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '部门', field: 'department', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '建档时间', field: 'filingTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTime(value, row, index);
            }
        },
        {title: '预约时间', field: 'appointmentTime', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTitle(value, row, index);
            }
        },
        {title: '回访状态', field: 'statuss', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '到诊时间', field: 'firstVisitDate', align: 'center', valign: 'middle', sortable: true, width: 170,
            formatter: function (value, row, index) {
                return _formatterTime(value, row, index);
            }
        },
        {title: '一级渠道', field: 'oneChannel', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '二级渠道', field: 'twoChannel', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '三级渠道', field: 'thrChannel', align: 'center', valign: 'middle', sortable: true, width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '一级媒介', field: 'oneMedium', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '二级媒介', field: 'twoMedium', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '三级媒介', field: 'thrMedium', align: 'center', valign: 'middle', sortable: true, width: 130,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '回访', field: 'huifang', align: 'center', valign: 'middle', sortable: true, width: 250,
            formatter: function (value, row, index) {
                return '<span title="' + value + '">' + value + '</span>'
            },
            cellStyle: function (value, row, index) {
                return {css: {"overflow": "hidden", "white-space": "nowrap", "text-overflow": "ellipsis"}}
            }
        },
        {title: '性别', field: 'customerSex', align: 'center', valign: 'middle', sortable: true, width: 80,
            formatter: function (value, row, index) {
                var sexValue = value === 1 ? '男' : value === 2 ? '女' : '未知';
                if (row.dealStatus === "已结账") {
                    return "<span style='color: green'>" + sexValue + "</span>"
                } else {
                    return sexValue;
                }
            }
        },
        {title: '年龄', field: 'customerAge', align: 'center', valign: 'middle', sortable: true, width: 80,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '开单状态', field: 'dealStatus', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '成交金额', field: 'money', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                if (row.dealStatus === "已结账") {
                    if (value == null || value === "") {
                        return "<span style='color: green'>0.00</span>"
                    } else {
                        return "<span style='color: green'>" + value + "</span>"
                    }
                } else {
                    return "0.00";
                }
            }
        },
        {title: '预约病种', field: 'appointmentPayService', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '访问病种', field: 'accessDisease', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '消费项目', field: 'expenditureProject', align: 'center', valign: 'middle', sortable: true, width: 110,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '初诊TC', field: 'tcName', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '关键词', field: 'keyWord', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        },
        {title: '微信号', field: 'wechatNumber', align: 'center', valign: 'middle', sortable: true, width: 100,
            formatter: function (value, row, index) {
                return _formatter(value, row, index);
            }
        }
    ];
    return columns;
};

ReservationsStoreRecordsTable.search = function () { // 查询预约客户列表
    ReservationsStoreRecordsTable.table.refresh({query: ReservationsStoreRecordsTable.formParams()});
    // ReservationsStoreRecordsTable.tongji();
    ReservationsStoreRecordsTable.moneyAccount();
};

ReservationsStoreRecordsTable.formParams = function () { // 新 市场预约表单查询提交参数
    var queryData = {};
    queryData['arrivalStore'] = multipleSelection($('#arrivalStore').val());
    queryData['department'] = $("#department").val(); //  部门
    queryData['reach'] = $("#marketInputPublic", parent.document).val();  //姓名   电话   微信  预约号
    queryData['appointmentPayService'] = $("#appointmentPayService").val();  //预约项目
    queryData['archiving'] = $("#archiving").val();   //建档人
    queryData['follower'] = $("#follower").val();   //跟进人
    queryData['accessDisease'] = $("#accessDisease").val();  //访问病种
    queryData['oneChannel'] = $("#oneChannel").val();  //一级渠道
    queryData['twoChannel'] = $("#twoChannel").val();    //二级渠道
    queryData['thrChannel'] = $("#thrChannel").val();    //三级渠道
    queryData['oneMedium'] = $("#oneMedium").val();  //一级渠道
    queryData['twoMedium'] = $("#twoMedium").val();    //二级渠道
    queryData['thrMedium'] = $("#thrMedium").val();    //三级渠道
    queryData['statuss'] = multipleSelection($('#statuss').val());
    queryData['belonger'] = $("#belonger").val();   //归属人
    queryData['startFirstVisitDate'] = $("#startFirstVisitDate").val();  //建档时间
    queryData['endFirstVisitDate'] = $("#endFirstVisitDate").val();
    queryData['area'] = multipleSelection($('#area').val());
    return queryData;
};

// ReservationsStoreRecordsTable.tongji = function () { // 统计建档，已到，未到 - 人数
//     //获取门诊、部门、建档人参数
//     var param1 = multipleSelection($('#arrivalStore').val());
//     var param2 = $("#department").val();   //部门
//     var param3 = $("#archiving").val();  //建档人
//     var param4 = $("#thrChannel").val(); //三级渠道
//     var param5 = $("#twoChannel").val();  //二级渠道
//     var param6 = $("#oneChannel").val();  //一级渠道
//     var param7 = multipleSelection($('#statuss').val());
//     var param8 = $("#accessDisease").val();  //访问病种
//     var param9 = $("#appointmentPayService").val();  //访问项目
//     var param10 = $("#follower").val();  //状态
//     var param11 = $("#belonger").val();  //状态
//     var date = new Date();
//     var currentWeek = date.getDay();
//     var stepSunDay = -currentWeek + 1;
//     if (currentWeek == 0) {stepSunDay = -7;}
//     var stepMonday = 7 - currentWeek;
//     var time = date.getTime();
//     var monday = new Date(time + stepSunDay * 24 * 3600 * 1000);
//     var sunday = new Date(time + stepMonday * 24 * 3600 * 1000);
//     var param12 = setDateTime(monday,0) + " " + "00:00:00";
//     var param13 = setDateTime(sunday,0) + " " + "23:59:59";
//     var param14 = multipleSelection($('#area').val());
//     var param15 = $("#marketInputPublic", parent.document).val();  //姓名   电话   微信  预约号
//     var param16 = $("#oneMedium").val(); //三级渠道
//     var param17 = $("#twoMedium").val();  //二级渠道
//     var param18 = $("#thrMedium").val();  //一级渠道
//     $.ajax({ // 发送ajax请求后台查询统计信息，赋值到对应的地方
//         type: "GET",
//         url: Feng.ctxPath + "/storeRecords/tongjiydjl",
//         data: {
//             param1: param1, param2: param2, param3: param3,
//             param4: param4, param5: param5, param6: param6,
//             param7: param7, param8: param8, param9: param9,
//             param10: param10, param11: param11,
//             param12: param12, param13: param13, param14: param14, param15: param15,
//             param16: param16, param17: param17, param18: param18
//         },
//         dataType: "json",
//         success: function (data) {
//             $("#daozhenToday").html(data[0].countNum);
//             $("#daozhenYesterday").html(data[1].countNum);
//             $("#daozhenThisWeek").html(data[2].countNum);
//             $("#daozhenMonth").html(data[3].countNum);
//             $("#daozhenLastMonth").html(data[4].countNum);
//         }
//     });
// };

ReservationsStoreRecordsTable.moneyAccount = function () { // 统计建档，已到，未到 - 金额
    $.ajax({
        type: "GET",
        url: Feng.ctxPath + '/storeRecords/accountjl',
        data: ReservationsStoreRecordsTable.formParams(),
        dataType: "json",
        success: function (data) {
            $('#recordMoney').html(data.totalMoney);
        }
    })
};

var parseParam = function (param) { // 把对象拼接成URL的键值对参数 param1=value1&param2=value2
    var paramStr = "";
    $.each(param, function (i) {
        paramStr += '&' + getSingleData(param, i);
    });
    return paramStr.substr(1);
};
var getSingleData = function (param, key) {
    return key + "=" + param[key];
};

ReservationsStoreRecordsTable.check = function () { // 检查是否选中
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length == 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        ReservationsStoreRecordsTable.seItem = selected[0];
        return true;
    }
};

ReservationsStoreRecordsTable.twoDevelopment = function () {
    if (this.check()) {
        var id = ReservationsStoreRecordsTable.seItem.id;
        $.ajax({
            url: Feng.ctxPath + "/reservation/updatetwoDevelopment/" + id,
            type: "post",
            success: function (data) {
                if(data==0){
                    alert("提示：该患者还没有到店记录")
                }else if(data==-1){
                    alert("提示：该患者已经被发起过二次开发，不能重复发起")
                }else {
                    var index = layer.open({
                        type: 2,
                        title: '二次开发',
                        area: ['50%', '60%'], //宽高
                        fix: true,
                        maxmin: true,
                        content: Feng.ctxPath + '/reservations/second_development/' + id
                    });
                    this.layerIndex = index
                }
            },
            error: function (data) {
                alert('没有权限，请联系系统管理员!');
                parent.layer.close(windowNameIndex)
            }
        })
    }
};

ReservationsStoreRecordsTable.getData = function () { // 片区筛选
    var area = multipleSelection($('#area').val());
    $.post(Feng.ctxPath + "/dept/getListByArea/"+area,function (data) {
        $('#arrivalStore').empty();
        for (var i = 0; i < data.length; i++) {
            $('#arrivalStore').append("<option value=" + data[i].simplename + ">" + data[i].simplename + "</option>");
        }
        $('#arrivalStore').selectpicker('refresh');
        $('#arrivalStore').selectpicker('render');
        ReservationsStoreRecordsTable.search();
    }, "json");
};

ReservationsStoreRecordsTable.getFollower = function () { // 添加跟进人
    var index = layer.open({
        type: 2,
        title: '添加跟进人',
        area: ['70%', '60%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservations/to_follower'
    });
    this.layerIndex = index;
};

ReservationsStoreRecordsTable.getBelonger = function () { // 添加归属人
    var index = layer.open({
        type: 2,
        title: '添加归属人',
        area: ['70%', '60%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservations/to_belonger'
    });
    this.layerIndex = index;
};

ReservationsStoreRecordsTable.getArchiving = function () { // 选择建档人
    var index = layer.open({
        type: 2,
        title: '选中建档人',
        area: ['70%', '60%'], //宽高
        fix: true, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/reservation/to_archiving'
    });
    this.layerIndex = index;
};

ReservationsStoreRecordsTable.reservationsExportYDMZ = function () { // 导出
    var param = parseParam(ReservationsStoreRecordsTable.formParams());
    location.href = Feng.ctxPath + '/storeRecords/reservationsExportYDMZ?' + param;
};

ReservationsStoreRecordsTable.resetSearch = function () { // 重置
    $("#marketInputPublic", parent.document).val("");
    $("#archiving").val("");
    $("#follower").val("");
    $("#accessDisease").val("");
    $("#statuss").selectpicker('deselectAll');
    $("#belonger").val("");
    $("#startFirstVisitDate").val("");
    $("#endFirstVisitDate").val("");
    $("#appointmentPayService").val("");
    $("#oneChannel").val("请选择");
    $("#twoChannel").val("请选择");
    $("#thrChannel").val("请选择");
    $("#oneMedium").val("请选择");
    $("#twoMedium").val("请选择");
    $("#thrMedium").val("请选择");
    $("#area").selectpicker('deselectAll');
    $("#arrivalStore").selectpicker('deselectAll');
    $("#department").val("");
    ReservationsStoreRecordsTable.search();
};

ReservationsStoreRecordsTable.supplement = function () { // 提交添加补单预约客户
    if (this.check()) {
        if (ReservationsStoreRecordsTable.seItem.department != "直接上门") {
            alert("不为直接上门患者，不能补单！");
            return;
        }
        var index = layer.open({
            type: 2,
            title: '补单操作',
            area: ['50%', '60%'], //宽高
            fix: true, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/reservations/supplement/' + ReservationsStoreRecordsTable.seItem.id
        });
    }
};

ReservationsStoreRecordsTable.today = function () { // 点击上面状态筛选表格
    $("#startFirstVisitDate").val(setDateTime(new Date(),0) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setDateTime(new Date(),0) + " " + "23:59:59");
    ReservationsStoreRecordsTable.search();
};

ReservationsStoreRecordsTable.yesterday = function () { // 昨天
    $("#startFirstVisitDate").val(setDateTime(new Date(),1) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setDateTime(new Date(),1) + " " + "23:59:59");
    ReservationsStoreRecordsTable.search();
};

ReservationsStoreRecordsTable.thisWeek = function () { // 本周
    var date = new Date();
    var currentWeek = date.getDay();
    var stepSunDay = -currentWeek + 1;
    if (currentWeek == 0) {stepSunDay = -7;}
    var stepMonday = 7 - currentWeek;
    var time = date.getTime();
    var monday = new Date(time + stepSunDay * 24 * 3600 * 1000);
    var sunday = new Date(time + stepMonday * 24 * 3600 * 1000);
    $("#startFirstVisitDate").val(setDateTime(monday,0) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setDateTime(sunday,0) + " " + "23:59:59");
    ReservationsStoreRecordsTable.search();
};

ReservationsStoreRecordsTable.thisMonth = function () { // 本月
    $("#startFirstVisitDate").val(firstMonthTime(new Date(),0) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setMonthTime(new Date(),0) + " " + "23:59:59");
    ReservationsStoreRecordsTable.search();
};

ReservationsStoreRecordsTable.lastMonth = function () { // 上个月
    $("#startFirstVisitDate").val(firstMonthTime(new Date(),1) + " " + "00:00:00");
    $("#endFirstVisitDate").val(setMonthTime(new Date(),1) + " " + "23:59:59");
    ReservationsStoreRecordsTable.search();
};

$("#marketSearchAll", parent.document).click(function () { // 主页搜索
    ReservationsStoreRecordsTable.search();
});

function phonePrivileges(){   //隐藏手机号
    var phonePrivileges=parent.$("#phonePrivileges").val();
    if(phonePrivileges == 2){
        $('#ReservationsStoreRecordsTable').bootstrapTable('hideColumn', 'customerPhone');
    }
}
$(function () {
    var defaultColunms = ReservationsStoreRecordsTable.initColumn();
    var table = new BSTable(ReservationsStoreRecordsTable.id, "/storeRecords/list", defaultColunms);
    table.setPaginationType("server");
    table.setQueryParams(ReservationsStoreRecordsTable.formParams());
    ReservationsStoreRecordsTable.table = table.init();
    ReservationsStoreRecordsTable.today();
    menuNameHideColumn($("#menuName").val(),'ReservationsStoreRecordsTable');
    $(document).on('click', '#laydate_clear,#laydate_today,#laydate_ok', function () {ReservationsStoreRecordsTable.search()});
    $("#oneChannel").change(function () {$("#twoChannel").val('请选择');$("#thrChannel").val('请选择');ReservationsStoreRecordsTable.search()});
    $("#twoChannel").change(function () {$("#thrChannel").val('请选择');ReservationsStoreRecordsTable.search()});
    $("#thrChannel").change(function () {ReservationsStoreRecordsTable.search()});
    $("#oneMedium").change(function () {$("#twoMedium").val('请选择');$("#thrMedium").val('请选择');ReservationsStoreRecordsTable.search()});
    $("#twoMedium").change(function () {$("#thrMedium").val('请选择');ReservationsStoreRecordsTable.search()});
    $("#thrMedium").change(function () {ReservationsStoreRecordsTable.search()});
    checkDate = function () {ReservationsStoreRecordsTable.search()};
    callbackTable = function () {ReservationsStoreRecordsTable.search()};
    phonePrivileges();
});